package com.zkingsoft.actions.app.interfaces;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.zkingsoft.constance.SystemConstance;
import com.zkingsoft.constraint.BaseController;
import com.zkingsoft.exception.GlobleException;
import com.zkingsoft.model.distribution.DisCoupon;
import com.zkingsoft.model.distribution.DisCouponRule;
import com.zkingsoft.model.distribution.DisDesigner;
import com.zkingsoft.model.distribution.DisMembers;
import com.zkingsoft.model.distribution.DisRebateFlow;
import com.zkingsoft.model.distribution.DisWithdrawalsFlow;
import com.zkingsoft.plugin.message.Sendsms;
import com.zkingsoft.pojo.AjaxResult;
import com.zkingsoft.services.distribution.DisCouponRuleService;
import com.zkingsoft.services.distribution.DisCouponService;
import com.zkingsoft.services.distribution.DisDesignerService;
import com.zkingsoft.services.distribution.DisMembersService;
import com.zkingsoft.services.distribution.DisRebateFlowService;
import com.zkingsoft.services.distribution.DisWithdrawalsFlowService;
import com.zkingsoft.sqlUtil.ServiceUtil;
import com.zkingsoft.util.EncrypUtil;
import com.zkingsoft.util.StringUtils;
import com.zkingsoft.util.WebUtil;

@Controller
@RequestMapping(value = "app/users")
public class AppUsersController extends BaseController {

	@Resource
	private ServiceUtil serviceUtil;

	@Resource
	private DisDesignerService userService;

	@Resource
	private DisRebateFlowService disRebateFlowService;

	@Resource
	private DisMembersService disMembersService;

	@Resource
	private DisCouponService disCouponService;

	@Resource
	private DisWithdrawalsFlowService disWithdrawalsFlowService;

	@Resource
	private DisCouponRuleService disCouponRuleService;

	/**
	 * 前往个人中心页面
	 */
	@RequestMapping(value = "/toUserIndex")
	public String toUserIndex() {
		DisDesigner appLoginUser = (DisDesigner) WebUtil
				.getSessionAttribute(SystemConstance.APP_LOGIN_KEY);
		DisDesigner designer = userService.findById(appLoginUser.getDesId());
		// designer.setDesName(StringUtils.convertUnicode(designer.getDesName()));
		WebUtil.setRequestAttribute("designer", designer);

		DisDesigner query = new DisDesigner();
		query.setDesParentId(designer.getDesId());
		int subNum = userService.findTotal(query);
		WebUtil.setRequestAttribute("subNum", subNum);

		return "app/users/user_index";
	}

	/**
	 * 前往我的下级页面
	 */
	@RequestMapping(value = "/toMySubList")
	public String toMySubs() {
		DisDesigner appLoginUser = (DisDesigner) WebUtil
				.getSessionAttribute(SystemConstance.APP_LOGIN_KEY);

		DisDesigner query = new DisDesigner();
		query.setDesParentId(appLoginUser.getDesId());
		List<DisDesigner> subList = userService.findMySubList(appLoginUser
				.getDesId());
		WebUtil.setRequestAttribute("subList", subList);

		return "app/users/user_sub_list";
	}

	/**
	 * 前往设计师返点详细列表页面
	 */
	@RequestMapping(value = "/toRebateFlow")
	public String toRebateFlow(Long desId, String month) {
		List<DisRebateFlow> rebateFlows = disRebateFlowService.findRebateFlows(
				desId, month);
		WebUtil.setRequestAttribute("rebateFlows", rebateFlows);

		Map<String, BigDecimal> totalMap = disRebateFlowService
				.findTotalRebate(desId, month);
		WebUtil.setRequestAttribute("totalRecord", totalMap.get("totalRecord"));
		WebUtil.setRequestAttribute("totalRebate", totalMap.get("totalRebate"));

		List<String> monthList = disRebateFlowService.findAllMonth();
		WebUtil.setRequestAttribute("monthList", monthList);

		WebUtil.setRequestAttribute("desId", desId);
		WebUtil.setRequestAttribute("month", month);

		return "app/users/user_rebate_flow";
	}

	/**
	 * 前往我的客户页面
	 */
	@RequestMapping(value = "/toMyCusList")
	public String toMyCusList() {
		DisDesigner appLoginUser = (DisDesigner) WebUtil
				.getSessionAttribute(SystemConstance.APP_LOGIN_KEY);

		List<DisMembers> cusList = disMembersService.findMyCusList(appLoginUser
				.getDesId());
		WebUtil.setRequestAttribute("cusList", cusList);

		return "app/users/user_cus_list";
	}
	
	/**
	 * 去添加客户页
	 */
	@RequestMapping(value="/toAddCus")
	public String toAddCus() {
		DisDesigner appLoginUser = (DisDesigner) WebUtil
				.getSessionAttribute(SystemConstance.APP_LOGIN_KEY);

		List<DisMembers> cusList = disMembersService.findMyCusList(appLoginUser
				.getDesId());
		WebUtil.setRequestAttribute("cusList", cusList);

		return "app/users/user_cus_form";
	}
	/**
	 * 添加客户
	 */
	@RequestMapping(value="/doAddCus")
	@ResponseBody
	public AjaxResult doAddCus(DisMembers disMembers) {
		DisDesigner appLoginUser = (DisDesigner) WebUtil.getSessionAttribute(SystemConstance.APP_LOGIN_KEY);
		if(appLoginUser == null) {
			return new AjaxResult(AjaxResult.STATUS_ERR, null, "登录失效，请重新登录！");
		}
		disMembers.setMbAddTime(new Date());
		disMembers.setDesId(appLoginUser.getDesId());
		int i = disMembersService.add(disMembers);
		if (i > 0) {
			return new AjaxResult(AjaxResult.STATUS_OK, null, "客户添加成功");
		} else {
			return new AjaxResult(AjaxResult.STATUS_ERR, null, "客户添加失败");
		}
		
	}

	/**
	 * 前往我的优惠券页面
	 */
	@RequestMapping(value = "/toMyCouponList")
	public String toMyCouponList() {
		
		DisDesigner appLoginUser = (DisDesigner) WebUtil.getSessionAttribute(SystemConstance.APP_LOGIN_KEY);
		List<DisCoupon> couponList = disCouponService
				.findMyCouponList(appLoginUser.getDesId());
		WebUtil.setRequestAttribute("couponList", couponList);

		return "app/users/user_coupon_list";
	}

	/**
	 * 生成我的优惠券
	 */
	@RequestMapping(value = "/createCoupon")
	@ResponseBody
	public AjaxResult createCoupon(Long couponRuleId) {
		DisDesigner appLoginUser = (DisDesigner) WebUtil
				.getSessionAttribute(SystemConstance.APP_LOGIN_KEY);

		DisCoupon coupon = new DisCoupon();
		coupon.setDesId(appLoginUser.getDesId());
		coupon.setCouponRuleId(couponRuleId);
		coupon.setCouponCreateTime(new Date());
		coupon.setCouponState("1"); // 1.待分享 2.已分享 3.已使用
		coupon.setCouponCode(StringUtils.getRandomString(10));
		int i = disCouponService.add(coupon);
		if (i > 0) {
			return new AjaxResult(AjaxResult.STATUS_OK, null, "优惠券添加成功");
		} else {
			return new AjaxResult(AjaxResult.STATUS_ERR, null, "优惠券添加失败");
		}
	}

	/**
	 * 提现
	 */
	@RequestMapping(value = "/doWithdrawals")
	@ResponseBody
	public AjaxResult doWithdrawals(DisWithdrawalsFlow disWithdrawalsFlow) {
		DisDesigner appLoginUser = (DisDesigner) WebUtil
				.getSessionAttribute(SystemConstance.APP_LOGIN_KEY);
		DisDesigner disDesigner = userService.findById(appLoginUser.getDesId());
		if (disWithdrawalsFlow.getFlowMoney() == null
				|| disWithdrawalsFlow.getFlowMoney().equals(BigDecimal.ZERO)) {
			return new AjaxResult(AjaxResult.STATUS_ERR, null, "提现金额不能为空");
		}
		if (disDesigner.getDesRebate() == null
				|| disDesigner.getDesRebate().compareTo(
						disWithdrawalsFlow.getFlowMoney()) == -1) {
			return new AjaxResult(AjaxResult.STATUS_ERR, null, "余额不足");
		}

		disWithdrawalsFlow.setDesId(appLoginUser.getDesId());
		disWithdrawalsFlow.setFlowState("1"); // 1.未支付 2.已支付
		int i = disWithdrawalsFlowService.add(disWithdrawalsFlow);
		if (i > 0) {
			disDesigner.setDesRebate(disDesigner.getDesRebate().subtract(
					disWithdrawalsFlow.getFlowMoney()));
			userService.modifyByModel(disDesigner);

			return new AjaxResult(AjaxResult.STATUS_OK, null, "提现申请成功，请等待审核");
		} else {
			return new AjaxResult(AjaxResult.STATUS_ERR, null, "提现申请失败");
		}
	}

	/**
	 * 获取所有的优惠券规则
	 */
	@RequestMapping(value = "/getAllCouponRules")
	@ResponseBody
	public AjaxResult getAllCouponRules() {
		List<DisCouponRule> dataList = disCouponRuleService.getAllRules();

		return new AjaxResult(AjaxResult.STATUS_OK, dataList);
	}
	
	@RequestMapping(value = "/shareSucess")
	@ResponseBody
	public AjaxResult shareSucess(Long couponId) {
		DisCoupon disCoupon = disCouponService.findById(couponId);
		if(disCoupon != null) {
			disCoupon.setCouponState("2");
			disCouponService.modifyByModel(disCoupon);
		}
		return new AjaxResult(AjaxResult.STATUS_ERR, "app/users/toMyCouponList", "");
	}
	
	/**
	 * 前往修改我的信息
	 */
	@RequestMapping(value = "/toEditInfo")
	public String toEditInfo() {
		
		DisDesigner appLoginUser = (DisDesigner) WebUtil.getSessionAttribute(SystemConstance.APP_LOGIN_KEY);
		DisDesigner disDesigner = userService.findById(appLoginUser.getDesId());
		WebUtil.setRequestAttribute("designer", disDesigner);

		return "app/users/user_info";
	}
	
	/**
	 * 修改我的信息
	 */
	@RequestMapping(value = "/doEditInfo")
	@ResponseBody
	public AjaxResult doEditInfo(DisDesigner disDesigner) {
		DisDesigner appLoginUser = (DisDesigner) WebUtil.getSessionAttribute(SystemConstance.APP_LOGIN_KEY);
		
		disDesigner.setDesId(appLoginUser.getDesId());
		userService.modifyByModel(disDesigner);
		
		return new AjaxResult(AjaxResult.STATUS_OK, "修改成功！");
	}
	
	/**
	 * 前往修改我的密码
	 */
	@RequestMapping(value = "/toEditPassword")
	public String toEditPassword() {

		return "app/users/user_password";
	}
	
	/**
	 * 修改我的密码
	 */
	@RequestMapping(value = "/doEditPassword")
	@ResponseBody
	public AjaxResult doEditPassword(String newPassword, String code) {
		DisDesigner appLoginUser = (DisDesigner) WebUtil.getSessionAttribute(SystemConstance.APP_LOGIN_KEY);
		DisDesigner disDesigner = userService.findById(appLoginUser.getDesId());
		
		if (WebUtil.getSession().getAttribute(PMC) == null) { // 判断验证码是否失效
			return new AjaxResult(AjaxResult.STATUS_ERR, "验证码已失效！");
		}
		if (!disDesigner.getDesAccount().equals(WebUtil.getSession().getAttribute(PHONE))) { // 判断手机是否为发送短信的手机
			return new AjaxResult(AjaxResult.STATUS_ERR, "手机号未验证！");
		}
		if (!WebUtil.getSession().getAttribute(PMC).equals(code)) { // 判断验证码是否正确
			return new AjaxResult(AjaxResult.STATUS_ERR, null, "验证码错误!");
		}
		// 密码加密
		try {
			disDesigner.setDesPassword(EncrypUtil.getMD5(newPassword));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		int i = userService.modifyByModel(disDesigner);
		if (i > 0) {
			// 重新登录
			WebUtil.getSession().removeAttribute(PMC);
			WebUtil.getSession().removeAttribute(PHONE);
			WebUtil.getSession().removeAttribute(SystemConstance.APP_LOGIN_KEY);
			AjaxResult result = new AjaxResult(AjaxResult.STATUS_OK, "app/authorize", "密码修改成功！");
			return result;
		} else {
			return new AjaxResult(AjaxResult.STATUS_ERR, null, "密码修改失败！");
		}
	}
	
	
	/** 修改密码验证码 */
	private static final String PMC = "PwdMsgCode";
	/** 手机号 */
	private static final String PHONE = "Phone";
	/**
	 * 获取修改密码的验证码
	 */
	@RequestMapping(value = "/getPwdMsgCode")
	public @ResponseBody AjaxResult getMsgCode() {
		DisDesigner appLoginUser = (DisDesigner) WebUtil.getSessionAttribute(SystemConstance.APP_LOGIN_KEY);
		if(appLoginUser == null) {
			return new AjaxResult(AjaxResult.STATUS_ERR, "登录超时，请重新登录！");
		}
		DisDesigner user = userService.findById(appLoginUser.getDesId());
		String tel = user.getDesAccount();
		try {
			String code = Sendsms.sendSms(tel);
			if(code==null || "".equals(code)){
				return new AjaxResult(AjaxResult.STATUS_ERR, null,"验证码发送失败");
			}
			WebUtil.getSession().setAttribute(PMC, code);
			// // 获取验证码
//			WebUtil.setSessionAttribute(YZM, "1234");
		} catch (Exception e) {
			throw new GlobleException("验证码发送失败！");
		}

		WebUtil.setSessionAttribute(PHONE, tel);
		return new AjaxResult(AjaxResult.STATUS_OK, "验证码发送成功！");
		
	}
}
